package com.ytjj.qmyx.mall.service.impl;

import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.constants.ProductRecordConstant;
import com.ytjj.qmyx.mall.enums.ProductStatusEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.EvaluationProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class EvaluationProductServiceImpl implements EvaluationProductService {

    @Resource
    private EvaluationProductMapper evaluationProductMapper;

    @Resource
    private EvaluationProductImgMapper evaluationProductImgMapper;

    @Resource
    private ProductImgMapper productImgMapper;

    @Resource
    private EvaluationProductSpecMapper evaluationProductSpecMapper;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;
    @Resource
    private ProductSpecMapper productSpecMapper;

    @Override
    public EvaluationProductResponse getProductById(Integer id, String modular) {
        EvaluationProduct evaluationProduct = evaluationProductMapper.selectByPrimaryKey(id);
        Optional.ofNullable(evaluationProduct)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));
        if (evaluationProduct.getStatus().byteValue() != ProductStatusEnums.UP.getValue()) {
            throw new ApiException(ResultCode.NO_PRODUCT);
        }
        // pv值加+1
        evaluationProduct.setPv(evaluationProduct.getPv() + 1);
        evaluationProductMapper.updateByPrimaryKeySelective(evaluationProduct);

        ProductImgExample example = new ProductImgExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andProductIdEqualTo(id);
        List<ProductImg> productImgList = productImgMapper.selectByExample(example);
        Map<String, List<ProductImg>> map = productImgList.stream()
                .collect(Collectors.groupingBy(ProductImg::getType));
        EvaluationProductResponse productResponse = new EvaluationProductResponse(evaluationProduct)
                .setImgMapList(map);
        return productResponse;
    }

    @Override
    public EvaluationProductSpecResponse getProductSpecInfoById(Integer specId) {
        return new EvaluationProductSpecResponse(evaluationProductSpecMapper.selectByPrimaryKey(specId));
    }

}
